//
//  ForumDetailViewController.m
//  HubeiHotel
//
//  Created by LiBenCan on 17/11/15.
//  Copyright © 2017年 张露杰. All rights reserved.
//

#import "ForumDetailViewController.h"
#import "HBHCommentViewController.h"
#import "ReportViewController.h"

#import "HBHPostDetailCell.h"
#import "CommentCell.h"

#import "chooseBtnView.h"
@interface ForumDetailViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableV;
@property (nonatomic, strong) UIView *btnView;//底部按钮
@property (nonatomic, strong) UIView *headerCommentView;//评论区头
@property (nonatomic, strong) chooseBtnView *leftBtn;
@property (nonatomic, strong) chooseBtnView *rightBtn;

@property (nonatomic, retain) NSMutableDictionary *detail;
@property (nonatomic, retain) NSMutableArray *postComments;
@property (nonatomic) NSInteger pageNo;




@end

@implementation ForumDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _postComments = [NSMutableArray new];
    _pageNo = 1;
    [self initTitleWithTitle:@"帖子详情"];
    [self initLeftBarButtonWithImage:@"back"];
    [self initRightBarButtonWithTitle:@"举报" andTitleColor:[UIColor whiteColor] andFont:16*screenW_6];
    [self.view addSubview:self.tableV];
    [self.view addSubview:self.btnView];
    [self getDetail];
    [self getPostCommentList];
}

-(void)onTapRightBarButton
{
    if ([_detail[@"userId"] isEqualToString:[Storage getToken]]) {
        [self deletePost];
    }else{
        ReportViewController *vc = [ReportViewController new];
        vc.postId = _postId;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
-(UITableView *)tableV//创建视图
{
    if (!_tableV) {
        _tableV = [[UITableView alloc] initWithFrame:CGRectMake(0,0, SCREENW, SCREENH-64-50*screenW_6) style:UITableViewStyleGrouped];
//        _tableV.estimatedRowHeight = 180*screenW_6;
        _tableV.backgroundColor = backColor;
        _tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableV.showsVerticalScrollIndicator = NO;
        _tableV.delegate = self;
        _tableV.dataSource = self;
        //刷新
        _tableV.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            //            _PageNumber = 1;
            //            [self addTravelRequest:YES];
            [_postComments removeAllObjects];
            _pageNo = 1;
            [_tableV.mj_footer endRefreshingWithNoMoreData];
            [self getPostCommentList];
        }];
        //加载
        _tableV.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            //            _PageNumber++;
            //            [self addTravelRequest:NO];
            _pageNo ++;
            [self getPostCommentList];
        }];
    }
    return _tableV;
}
#pragma Mark TableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        if (!_detail) {
            return 0;
        }
        return 1;
    }
    return _postComments.count;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return 40*screenW_6;
    }
    return 0.00001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 1) {
        return 50*screenW_6;
    }
    return 10*screenW_6;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self) weakSelf = self;
    if (indexPath.section == 0) {//帖子详情Cell
        HBHPostDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HBHPostDetailCell"];
        if (cell == nil) {
            cell = [[HBHPostDetailCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HBHPostDetailCell"];
        }
        [cell loadCellWithData:_detail];
        cell.commentTapBlock = ^(NSInteger index){
            if (index == 0) {
                
            }else if (index == 1){
                if ([weakSelf.detail[@"isClick"] boolValue]) {
                    [TomamaUI creatAlertWithTarget:weakSelf message:@"已点过赞" timeInterval:2];
                }else{
                    [weakSelf.detail setObject:@"1" forKey:@"isClick"];
                    [weakSelf.detail setObject:[NSString stringWithFormat:@"%ld",[weakSelf.detail[@"clickNum"] integerValue] + 1>0?[weakSelf.detail[@"clickNum"] integerValue] + 1:0] forKey:@"clickNum"];
                    [tableView reloadData];
                    [weakSelf clickPost];
                }
            }
        };
        
        cell.folloBlock = ^(){
            [weakSelf followPost];
        };
        
        return cell;
    }else//帖子评论Cell
    {
        CommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommentCell"];
        if (!cell) {
            cell = [[CommentCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CommentCell"];
        }
        [cell loadCellWithData:_postComments[indexPath.row]];
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat h;
    if (indexPath.section == 0) {
        h += [TomamaUI getStringHeightWith:_detail[@"content"] andWeith:SCREENW - 30*screenW_6 andFont:[UIFont systemFontOfSize:14*screenW_6]];
        NSArray *imags = _detail[@"imgList"];
        if (imags.count) {
            h += 175*screenW_6;
        }
        return h + 105*screenW_6;
    }else if (indexPath.section == 1){
        h += [TomamaUI getStringHeightWith:_postComments[indexPath.row][@"content"] andWeith:SCREENW - 68*screenW_6 andFont:[UIFont systemFontOfSize:14*screenW_6]];
        return 92*screenW_6 + h;
    }
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return self.headerCommentView;
    }
    return nil;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 1) {//区尾结束照片
        UIImageView *footImageV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0,SCREENW, 50*screenW_6)];
        footImageV.image = [UIImage imageNamed:@"Forumend"];
        return footImageV;
    }
    return nil;
}
-(UIView *)headerCommentView//评论区头
{
    if (!_headerCommentView) {
        _headerCommentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENW,40*screenW_6)];
        _headerCommentView.backgroundColor = [UIColor whiteColor];

        UILabel *commentLab = [TomamaUI createLabel:CGRectMake(15*screenW_6, 0, SCREENW, 39*screenW_6) textAligment:0 font:[UIFont systemFontOfSize:14*screenW_6] textColor:[UIColor colorWithHexString:@"#555555"] text:@"热门评论"];
        [_headerCommentView addSubview:commentLab];
        
        [_headerCommentView addSubview:[ToolViewVC addCellLineLab:CGRectMake(15*screenW_6, 39*screenW_6, SCREENW-30*screenW_6, 1*screenW_6)]];
    }
    return _headerCommentView;
}
-(UIView *)btnView
{
    if (!_btnView) {//底部btnView
        _btnView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREENH-64-49*screenW_6, SCREENW, 49*screenW_6)];
        
        //评论
        _leftBtn = [[chooseBtnView alloc]initWithFrame:CGRectMake(0, 0, SCREENW/2, 49*screenW_6) Title:@"评论" NomolImageV:@"pinglunGreen" SelectImageV:@"pinglunGreen" IsSelect:NO];
        [_btnView addSubview:_leftBtn];
        _leftBtn.userInteractionEnabled = YES;
        UITapGestureRecognizer *commentTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(commentTap)];
        [_leftBtn addGestureRecognizer:commentTap];
        
        //点赞
        _rightBtn = [[chooseBtnView alloc]initWithFrame:CGRectMake( SCREENW/2+1, 0,SCREENW/2-1, 49*screenW_6) Title:@"点赞" NomolImageV:@"likeGreen" SelectImageV:@"likeGreen" IsSelect:NO];
        [_btnView addSubview:_rightBtn];
        _rightBtn.userInteractionEnabled = YES;
        UITapGestureRecognizer *likeTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(likeTap)];
        [_rightBtn addGestureRecognizer:likeTap];
        
    }
    return _btnView;
}

-(void)commentTap//评论点击事件
{
    HBHCommentViewController *vc = [HBHCommentViewController new];
    vc.postId = _postId;
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)likeTap//点赞点击事件
{
    if ([_detail[@"isClick"] boolValue]) {
        [TomamaUI creatAlertWithTarget:self message:@"已点过赞" timeInterval:2];
    }else{
        [_detail setObject:@"1" forKey:@"isClick"];
        [_detail setObject:[NSString stringWithFormat:@"%ld",[_detail[@"clickNum"] integerValue] + 1>0?[_detail[@"clickNum"] integerValue] + 1:0] forKey:@"clickNum"];
        [_tableV reloadData];
        [_rightBtn IsChoose:[_detail[@"isClick"] boolValue]];
        [self clickPost];
    }
}

#pragma mark request
-(void)getDetail
{
    [HudHelper showProgressHudWithMessage:@"" toView:self.view];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [HttpRequest PostrequestUrl:@"/post/postDetail" Dic:@{@"id":_postId,@"jdUserId":[Storage getToken]} completion:^(NSDictionary *responseDic) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [HudHelper hideHudToView:self.view];
                if ([responseDic[@"success"] boolValue]) {
                    _detail = [NSMutableDictionary dictionaryWithDictionary:responseDic[@"data"]];
                    [_rightBtn IsChoose:[_detail[@"isClick"] boolValue]];
                    [_tableV reloadData];
                    if ([_detail[@"userId"] isEqualToString:[Storage getToken]]) {
                        [self initRightBarButtonWithTitle:@"删除" andTitleColor:[UIColor whiteColor] andFont:16*screenW_6];
                    }
                }else{
                    [TomamaUI creatAlertWithTarget:self message:responseDic[@"msg"] timeInterval:2];
                }
            });
        }];
    });
}

-(void)getPostCommentList
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [HttpRequest PostrequestUrl:@"/post/postCommentList" Dic:@{@"postId":_postId,@"pageNo":[NSString stringWithFormat:@"%ld",_pageNo],@"pageSize":@"10"} completion:^(NSDictionary *responseDic) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [HudHelper hideHudToView:self.view];
                if ([responseDic[@"success"] boolValue]) {
                    if ([responseDic[@"count"] integerValue] > _postComments.count) {
                        [_postComments addObjectsFromArray:responseDic[@"data"]];
                    }
                }else{
                    [TomamaUI creatAlertWithTarget:self message:responseDic[@"msg"] timeInterval:2];
                }
                [_tableV reloadData];
                if ([_tableV.mj_header isRefreshing]) {
                    [_tableV.mj_header endRefreshing];
                }
                if ([_tableV.mj_footer isRefreshing]) {
                    if ([responseDic[@"count"] integerValue] <= _postComments.count) {
                        [_tableV.mj_footer endRefreshingWithNoMoreData];
                    }else{
                        [_tableV.mj_footer endRefreshing];
                    }
                }
            });
        }];
    });
}

-(void)clickPost
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [HttpRequest PostrequestUrl:@"/post/clickPost" Dic:@{@"post.id":_postId,@"user.id":[Storage getToken]} completion:^(NSDictionary *responseDic) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([responseDic[@"success"] boolValue]) {
                    
                }else{
                    [_detail setObject:@"0" forKey:@"isClick"];
                    [_detail setObject:[NSString stringWithFormat:@"%ld",[_detail[@"clickNum"] integerValue] - 1>0?[_detail[@"clickNum"] integerValue] - 1:0] forKey:@"clickNum"];
                    [_rightBtn IsChoose:[_detail[@"isClick"] boolValue]];
                    [_tableV reloadData];
                }
            });
        }];
    });
}

-(void)followPost
{
    NSString *url = @"/user/addFollow";
    if ([_detail[@"isFollow"] boolValue]) {
        url = @"/user/cancelFollow";
    }
    
    [HudHelper showProgressHudWithMessage:@"" toView:self.view];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [HttpRequest PostrequestUrl:url Dic:@{@"othersUser.id":_detail[@"userId"],@"ownUser.id":[Storage getToken]} completion:^(NSDictionary *responseDic) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [HudHelper hideHudToView:self.view];
                if ([responseDic[@"success"] boolValue]) {
                    NSString *msg = @"关注成功";
                    if ([_detail[@"isFollow"] boolValue]) {
                        [_detail setObject:@"0" forKey:@"isFollow"];
                        msg = @"取关成功";
                    }else{
                        [_detail setObject:@"1" forKey:@"isFollow"];
                    }
                    [_tableV reloadData];
                    [TomamaUI creatAlertWithTarget:self message:msg timeInterval:2];
                }else{
                    [TomamaUI creatAlertWithTarget:self message:responseDic[@"msg"] timeInterval:2];
                }
            });
        }];
    });
}

-(void)deletePost
{
    [HudHelper showProgressHudWithMessage:@"" toView:self.view];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [HttpRequest PostrequestUrl:@"/post/deletePost" Dic:@{@"id":_postId} completion:^(NSDictionary *responseDic) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [HudHelper showProgressHudWithMessage:@"" toView:self.view];
                if ([responseDic[@"success"] boolValue]) {
                    [self.navigationController popViewControllerAnimated:YES];
                    if (_deleteBlcok) {
                        _deleteBlcok(_postId);
                    }
                }else{
                    [TomamaUI creatAlertWithTarget:self message:responseDic[@"msg"] timeInterval:2];
                }
            });
        }];
    });
}
@end
